import 'package:flutter/material.dart';

class XJStarRating extends StatefulWidget {
  final double rating;
  final double maxRating;
  final int count;
  final double size;
  final Color normalColor;
  final Color selectColor;
  final Widget normalImage;
  final Widget selectImage;

  XJStarRating({
    @required this.rating,
    this.maxRating = 10,
    this.count = 5,
    this.size = 60,
    this.normalColor = const Color(0xffbbbbbb),
    this.selectColor = const Color(0xFFB71C1C),
    Widget normalImage,
    Widget selectImage,
  })  : this.normalImage = normalImage ??
            Icon(
              Icons.star_border,
              color: normalColor,
              size: size,
            ),
        this.selectImage = selectImage ??
            Icon(
              Icons.star,
              color: selectColor,
              size: size,
            );

  @override
  _XJStarRatingState createState() => _XJStarRatingState();
}

class _XJStarRatingState extends State<XJStarRating> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Row(
          mainAxisSize: MainAxisSize.min,
          children: buildNormalStarWidget(),
        ),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: buildSelectStarWidget(),
        )
      ],
    );
  }

  List<Widget> buildNormalStarWidget() {
    return List.generate(this.widget.count, (index) {
      return this.widget.normalImage;
    });
  }

  List<Widget> buildSelectStarWidget() {
    final star = this.widget.selectImage;
//    1.创建stars
    List<Widget> stars = [];
//  2.构造满填充的star
    double oneValue = widget.maxRating / widget.count;
    int entireCount = (widget.rating / oneValue).floor();
    for (int i = 0; i < entireCount; i++) {
      stars.add(star);
    }
//    3.构造部分填充的star
    double leftWidth = ((widget.rating / oneValue) - entireCount) * widget.size;
    final partStar = ClipRect(
      child: star,
      clipper: XJStartClipper(width: leftWidth),
    );
    stars.add(partStar);
    if (stars.length > widget.count) {
      return stars.sublist(0, widget.count);
    }
    return stars;
  }
}

class XJStartClipper extends CustomClipper<Rect> {
  double width;

  XJStartClipper({this.width});

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, this.width, size.height);
  }

  @override
  bool shouldReclip(XJStartClipper oldClipper) {
    return oldClipper.width != this.width;
  }
}
